<template>
    <div class="btns">
        <el-button type="primary" @click="openDailog('insert')">添加用户</el-button>
        <el-button type="danger" @click="openDailog('batchDeleted')">批量删除</el-button>
    </div>

    <el-table :data="userList" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" width="120" property="id"></el-table-column>
        <el-table-column property="name" label="姓名" width="120" />
        <el-table-column property="phone" label="手机" width="240" show-overflow-tooltip />
        <el-table-column property="email" label="邮箱" />
        <el-table-column property="createTime" label="创建时间" />
        <el-table-column label="操作">
            <!-- <el-button type="primary" @click="shouDetai(scope.row)">详情</el-button> -->
            <template #default="scope">
                <el-button type="primary" @click="shouDetail(scope.row)">详情</el-button>
                <el-button type="success" @click="openDailog('update', scope.row)">编辑</el-button>
                <el-button type="danger" @click="openDailog('delete', scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

    <el-pagination background layout="prev, pager, next" :total=total :page-size=pageSize @change="changePage" />
    <el-dialog v-if="titleDialog == '添加用户' || titleDialog == '修改用户'" v-model="dialogVisible" :title=titleDialog
        width="500" draggable>
        <template #footer>
            <el-form ref="insertUser" :model="userDetail" label-width="100px" :rules="userDetailRules">
                <el-form-item label="账号" prop="loginAct">
                    <el-input v-model="userDetail.loginAct" />
                </el-form-item>
                <el-form-item label="密码" prop="loginPwd" v-if="titleDialog != '修改用户'">
                    <el-input type="password" v-model="userDetail.loginPwd" />
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="userDetail.name" />
                </el-form-item>
                <el-form-item label="手机" prop="phone">
                    <el-input v-model="userDetail.phone" />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="userDetail.email" />
                </el-form-item>
                <el-form-item label="账号未过期" prop="isAcountNoExpiration">
                    <!-- <el-input v-model="userDetail.isAcountNoExpiration" /> -->
                    <el-radio-group v-model="userDetail.isAcountNoExpiration">
                        <el-radio :value="1">未过期</el-radio>
                        <el-radio :value="0">过期</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="账号未锁定" prop="isAcountNoLocked">
                    <!-- <el-input v-model="userDetail.isAcountNoLocked" /> -->
                    <el-radio-group v-model="userDetail.isAcountNoLocked">
                        <el-radio :value="1">未锁定</el-radio>
                        <el-radio :value="0">锁定</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="密码未过期" prop="isCredentialsNoExpiration" v-if="titleDialog != '修改用户'">
                    <!-- <el-input v-model="userDetail.isCredentialsNoExpiration" /> -->
                    <el-radio-group v-model="userDetail.isCredentialsNoExpiration">
                        <el-radio :value="1">未过期</el-radio>
                        <el-radio :value="0">过期</el-radio>
                    </el-radio-group>
                </el-form-item>

            </el-form>

            <el-button @click="submitForm">确定</el-button>
            <el-button type="primary" @click="dialogVisible = false">
                取消
            </el-button>

        </template>
    </el-dialog>

    <el-dialog v-else v-model="dialogVisible" :title=titleDialog width="500" draggable>
        <span>确认删除选中的人员吗</span>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="submitForm">确定</el-button>
                <el-button type="primary" @click="dialogVisible = false">
                    取消
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted } from 'vue'
import Request from '../http/Request.js'
import { ElTable } from 'element-plus'
import { useRouter } from 'vue-router'
import { ref } from 'vue'
import { ElMessage } from 'element-plus';

const dialogVisible = ref(false)
const $router = useRouter()
const userList = ref([]);
const total = ref(0);
const pageSize = ref(10);

const id = ref();
const ids = ref([]);

const userDetail = ref({
    loginAct: '',
    loginPwd: '',
    name: '',
    phone: '',
    email: '',
    isAcountNoExpiration: '', // Change to boolean
    isAcountNoLocked: '', // Change to boolean
    isCredentialsNoExpiration: '', // Change to boolean
})

const insertUser = ref(null)

const userDetailRules = ref({
    loginAct: [
        { required: true, message: '请输入账号', trigger: 'blur' },
    ],
    loginPwd: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 16, message: '密码长度为6-16位', trigger: 'blur' },
    ],
    name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
    ],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
    ],
    isAcountNoExpiration: [
        { required: true, message: '请选择账号是否过期', trigger: 'change' },
    ],
    isAcountNoLocked: [
        { required: true, message: '请选择账号是否锁定', trigger: 'change' },
    ],
    isCredentialsNoExpiration: [
        { required: true, message: '请选择密码是否过期', trigger: 'change' },
    ],
})


const openDailog = function (type, rowData) {
    dialogVisible.value = true;
    if (type === 'insert') {
        titleDialog.value = '添加用户';
        userDetail.value = {};
    }
    else if (type === 'update') {
        titleDialog.value = '修改用户';
        loadUserDetail(rowData.id);
    }
    else if (type === 'delete') {
        titleDialog.value = '删除用户';
        id.value = rowData.id;
    }
    else if (type === 'batchDeleted') {
        titleDialog.value = '批量删除'
    }
}
const idss=ref([])
const handleSelectionChange = (val) => {
    idss.value=[];
  
    val.forEach(element => {
        let id=element.id
        idss.value.push(id);
    });
}

const titleDialog = ref('添加用户');

const getUserList = function (params) {
    const res = Request.doGet('/api/users', params).then((res) => {
        // console.log(res)
        userList.value = res.data.list;
        total.value = res.data.total;
        pageSize.value = res.data.pageSize;
        // currentPage.value=res.data.currentPage;
        // pageCount.value=Math.ceil(total.value / pageSize.value);
    }).catch((err) => {
        throw new Error("获取用户列表失败：" + err);
    })
}
const changePage = function (currentPage, pageSize) {
    getUserList({
        current: currentPage,
        pageSize: pageSize
    })
}
const shouDetail = function (row) {
    $router.push({
        name: 'userDetail',
        params: {
            id: row.id
        }
    })
}
const shouDetai = function (row) {
    
}

const submitForm = function () {
    if (titleDialog.value == '删除用户') {
        
        Request.doDelete('/api/user/'+id.value).then((res) => {
            if (res.code == 200) {
                //提示message
                ElMessage({
                    message: '删除成功',
                    type: 'success',
                })
                //关闭dialog
                dialogVisible.value = false;
                //刷新列表
                getUserList();
            }else{
                ElMessage({
                    message: '删除失败'+res.msg,
                    type: 'error',
                })
            }
        }).catch((err) => {
            throw new Error("删除失败：" + err);
        })
        return
    }
    if (titleDialog.value == '批量删除') {
       
        Request.doDelete('/api/user', {
            ids:idss.value+''
        }).then((res) => {
            if(res.code == 200){
                ElMessage({
                    message: '删除成功',
                    type: 'success',
                })
                dialogVisible.value = false;
                getUserList();
            }else{
                ElMessage({
                    message: '删除失败',
                    type: 'error',
                })
            }
            // 表单数据有效
        }).catch((err) => {
            throw new Error("删除失败：" + err);
        })
        return
    }
    if (titleDialog.value == '添加用户'||titleDialog.value == '修改用户') {
    insertUser.value.validate((valid) => {
   
        if (valid) {
          
            if (titleDialog.value == '添加用户') {
                Request.doPost('/api/user', userDetail.value).then((res) => {
                 
                    // 表单数据有效
                }).then(() => {
                    // 提交表单成功后的操作
                    dialogVisible.value = false;
                    getUserList();
                }).catch((err) => {
                    throw new Error("添加用户失败：" + err);
                })
            } else if (titleDialog.value == '修改用户') {
             
                userDetail.value.loginPwd = '';
              
                Request.doPut('/api/user', {}, userDetail.value).then((res) => {
                 
                    // 表单数据有效
                }).then(() => {
                    // 提交表单成功后的操作
                    dialogVisible.value = false;
                    getUserList();
                }).catch((err) => {
                    throw new Error("修改用户失败：" + err);
                })
            }
        } else {
         
            return false;
        }
        
    });
    // if (titleDialog.value === '添加用户') {
    //     Request.doPost('/api/users', userDetail.value).then((res) => {
    //         console.log(res)
    //     }).catch((err) => {
    //         throw new Error("添加用户失败：" + err);
    //     })
    // } else if (titleDialog.value === '批量删除') {
    //     Request.doDelete('/api/users', userDetail.value).then((res) => {
    //         console.log(res)
    //     }).catch((err) => {
    //         throw new Error("批量删除失败：" + err);
    //     })
    // }
    }

}

const loadUserDetail = function (id) {
    Request.doGet('/api/user/' + id).then(res => {
        userDetail.value = res.data
        userDetail.value.isAcountNoExpiration = res.data.accountNoExpired
        //   userDetail.value.isPasswordNoExpiration=res.data.passwordNoExpired
        userDetail.value.isAcountNoLocked = res.data.accountNoLocked
        //   userDetail.value.isEnable=res.data.enabled
    })
}

const deletedBatch = function (ids) {

}

// 在组件挂载时调用获取用户列表
onMounted(() => {
    getUserList();
});
</script>
<style>
.btns {
    margin-bottom: 20px;
}

.el-pagination {
    margin-top: 20px;
    text-align: center;
}
</style>